package com.kedacom.freedomLabel.viewmodel;


import android.arch.lifecycle.LiveData;
import android.support.annotation.Nullable;

import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.base.BaseViewModel;
import com.kedacom.freedomLabel.model.DataControlResult;
import com.kedacom.freedomLabel.model.bean.Operator;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.model.db.DataCallback;
import com.kedacom.freedomLabel.model.db.DataLoader;
import com.kedacom.freedomLabel.model.db.dao.OperatorDao;
import com.kedacom.freedomLabel.utils.Cn2Spell;
import com.kedacom.lego.message.LegoMessageManager;
import com.kedacom.lego.mvvm.ObservableLiveDataField;

import java.util.List;

public class OperatorControlViewModel extends BaseViewModel {

    public ObservableLiveDataField<String> evNameText = new ObservableLiveDataField<>();
    public ObservableLiveDataField<String> evNumberText = new ObservableLiveDataField<>();
    public ObservableLiveDataField<String> evRemarkText = new ObservableLiveDataField<>();

    public void saveOperator() {
        String name = evNameText.getValue();
        String number = evNumberText.getValue();
        String remark = evRemarkText.getValue();

        Operator operator = new Operator();
        operator.name = name;
        operator.shortHand = Cn2Spell.getPinYinHeadChar(operator.name);
        operator.cardNumber = number;
        operator.remark = remark;
        operator.createTime = System.currentTimeMillis();

        OperatorDao dao = AppDatabase.getInstance().operatorDao();
        List<Operator>  operatorList = dao.get(number);

        if(operatorList.size()>0){
            DataControlResult result = new DataControlResult<>(operatorList.get(0));
            LegoMessageManager.getInstance().sendMessage(Options.MSG_ADD_EXISTS_RESULT, result);
        }else {
            LegoMessageManager.getInstance().sendMessage(Options.MSG_ADD_ITEM, operator);
        }

    }

    public void updateOperator(Operator operator) {
        String name = evNameText.getValue();
        String number = evNumberText.getValue();
        String remark = evRemarkText.getValue();

        operator.name = name;
        operator.shortHand = Cn2Spell.getPinYinHeadChar(operator.name);
        operator.cardNumber = number;
        operator.remark = remark;
        operator.updateTime = System.currentTimeMillis();

        LegoMessageManager.getInstance().sendMessage(Options.MSG_SAVE_ITEM, operator);
    }
}